<template>
  <a-modal
    :title="title"
    :width="800"
    :height="record && record.unqualifiedImg ? 1000 : 800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    destroyOnClose
  >
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel"> 关闭 </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" id="customerModal">
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品类型">
            <a-select
              placeholder="选择产品类型"
              showSearch
              :disabled="disableSubmit"
              optionFilterProp="children"
              v-decorator.trim="['productType', validatorRules.productType]"
            >
              <a-select-option
                @click="log(item)"
                v-for="(item, index) in purchaseTest"
                :key="index"
                :value="item.typeId"
              >
                {{ item.typeName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2" v-if="this.$router.currentRoute.name == '进货检验'">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="合同编码">
            <a-input
              placeholder="请输入合同编码"
              :disabled="disableSubmit"
              v-decorator.trim="['voucher', validatorRules.voucher]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2" v-if="this.$router.currentRoute.name !== '进货检验'">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="任务单号">
            <a-input
              placeholder="请输入任务单号"
              :disabled="disableSubmit"
              v-decorator.trim="['voucher', validatorRules.voucher]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2" v-if="this.$router.currentRoute.name == '进货检验'">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="供货商">
            <a-input placeholder="请输入供货商" :disabled="disableSubmit" v-decorator.trim="['vendor']" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2" v-if="this.$router.currentRoute.name !== '进货检验'">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="客户">
            <a-input placeholder="请输入客户名" :disabled="disableSubmit" v-decorator.trim="['vendor']" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="产品名称">
            <a-input
              placeholder="请输入产品名称"
              :disabled="disableSubmit"
              v-decorator.trim="['productName', validatorRules.productName]"
            />
          </a-form-item>
        </a-col>
        <!--  v-decorator.trim="['voucherType', validatorRules.voucherType]" -->
        <a-col :span="disableSubmit ? 12 : 24">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格型号">
            {{ !disableSubmit ? newMapObject : seeMapObject }}
            <a v-if="!disableSubmit" style="margin-left:20px" @click="clear()">清除</a>
          </a-form-item>
        </a-col>
        <div v-if="!disableSubmit">
          <a-col :span="11">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="规格">
              <a-select placeholder="请输入(非必填)" v-model="guiGeValue" showSearch optionFilterProp="children">
                <a-select-option
                  @click="checkout(item)"
                  v-for="(item, index) in modelArr"
                  :key="index"
                  :value="item.id"
                >
                  {{ item.attributeName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- v-decorator.trim="['attributes']" -->
          <a-col :span="10">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="内容">
              <a-input placeholder="请输入(非必填)" v-model="value" />
            </a-form-item>
          </a-col>
          <a-col :span="3">
            <a-button type="link" @click="addNewModel()">新增</a-button>
          </a-col>
        </div>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="检验日期">
            <a-date-picker
              style="width: 100%"
              format="YYYY-MM-DD"
              :disabled="disableSubmit"
              v-decorator.trim="['testDate', validatorRules.testDate]"
              placeholder="请输入检验日期"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="检验数量">
            <a-input
              placeholder="请输入检验数量"
              :disabled="disableSubmit"
              v-decorator.trim="['testNum', validatorRules.testNum]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="不合格数量">
            <a-input
              placeholder="请输入不合格数量"
              :disabled="disableSubmit"
              v-decorator.trim="['unqualifiedNum', validatorRules.unqualifiedNum]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2" v-if="false">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="合格率">
            <a-input :disabled="disableSubmit" v-decorator.trim="['qualifiedRate']" />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="检验处置">
            <a-input
              placeholder="请输入"
              :disabled="disableSubmit"
              v-decorator.trim="['disposal', validatorRules.disposal]"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2" v-if="!disableSubmit">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="上传">
            <!-- <a-upload
              name="file"
              accept="image/png,image/jpeg,image/webp,image/jpg"
              :beforeUpload="beforeUpload"
              :multiple="false"
              :headers="tokenHeader"
              :default-file-list="defaultFileList"
              :action="importExcelUrl"
              :showUploadList="true"
              v-decorator.trim="['unqualifiedImg']"
              @change="handleImportExcel"
              @preview="handlePreview"
            >
              <a-button :disabled="disableSubmit"> <a-icon type="upload" />上传</a-button>
            </a-upload> -->
            <!-- list-type="picture-card" -->

            <div class="clearfix">
              <a-upload
                accept="image/png,image/jpeg,image/webp,image/jpg"
                :beforeUpload="beforeUpload"
                :action="importExcelUrl"
                :headers="tokenHeader"
                :default-file-list="defaultFileList"
                @preview="handlePreview"
                @change="handleImportExcel"
              >
                <!-- <div v-if="defaultFileList.length < 8">
                  <a-icon type="plus" />
                  <div class="ant-upload-text">
                    上传
                  </div>
                </div> -->
                <a-button :disabled="disableSubmit"> <a-icon type="upload" />上传</a-button>
              </a-upload>
              <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancels">
                <img alt="example" style="width: 100%" :src="previewImage" />
              </a-modal>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="24 / 2">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="不合格原因">
            <a-input placeholder="请输入" :disabled="disableSubmit" v-decorator.trim="['unqualifiedContent']" />
          </a-form-item>
        </a-col>
        <a-col :span="24" v-if="disableSubmit">
          <a-form-item label="不合格图片">
            <div v-if="baseList.length != 0">
              <div v-for="(item, index) in baseList" :key="index">
                <p>{{ item.name }}</p>
                <img :src="item.fileUrl" alt="" id="imgSyle" />
              </div>

              <!-- <img :src="item.fileUrl" alt="" id="imgSyle" v-for="(item, index) in baseList" :key="index" /> -->
            </div>
            <a-empty v-else />
          </a-form-item>
        </a-col>
      </a-form>
    </a-spin>
    <!-- <a-modal :visible="previewVisible" :width="1000" :footer="null" @cancel="handleCancels()">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal> -->
  </a-modal>
</template>
<script>
import pick from 'lodash.pick'
import { addProduct, editSupplier, checkSupplier, getDateList, getModelList, getImgUrl } from '@/api/api'
import { getActionImg } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { autoJumpNextInput } from '@/utils/util'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}
export default {
  name: 'CustomerModal',
  mixins: [JeecgListMixin],
  data() {
    return {
      title: '操作',
      imgbase: null,
      baseList: [],
      visible: false,
      disableSubmit: false,
      record: null,
      guiGeValue: null,
      qualifiedRate: null,
      vaArr: [],
      guiArr: [],
      newMapObject: null,
      seeMapObject: null,
      selectValue: '',
      inputValue: '',
      guiG: null, //规格
      value: null, //规格内容
      selectModel: null,
      modelArr: ['颜色', '尺寸', '自定义'],
      model: {},
      isReadOnly: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      fileUrl: {
        importExcelUrl: '/systemConfig/upload' + '?' + `biz=test`
      },
      defaultFileList: [],
      confirmLoading: false,
      purchaseTest: [],
      form: this.$form.createForm(this),
      validatorRules: {
        productType: {
          rules: [{ required: true, message: '请选择类型名称!' }]
        },
        disposal: {
          rules: [{ required: true, message: '请选择检验处置!' }]
        },
        voucher: {
          rules: [{ required: true, message: '请选择!' }]
        },
        productName: {
          rules: [{ required: true, message: '请选择产品名称!' }]
        },
        testDate: {
          rules: [{ required: true, message: '请选择检验日期!' }]
        },
        testNum: {
          rules: [{ required: true, message: '请选择检验数量!' }]
        },
        unqualifiedNum: {
          rules: [{ required: true, message: '请选择不合格数量!' }]
        }
      },
      previewImage: '',
      previewVisible: false
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}${this.fileUrl.importExcelUrl}`
      // return `api${this.fileUrl.importExcelUrl}`
    }
  },
  mounted() {
    this.getList()
    this.getModelList()
  },
  methods: {
    //图片上传前做限制
    beforeUpload(file) {
      console.log('beforeUpload', file)
      return new Promise((resolve, reject) => {
        let isType =
          file.type === 'image/jpg' ||
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/webp'
        if (!isType) {
          this.$message.error('格式错误,只能上传jpg、jpeg、png、webp')
          return reject(false)
        }
        return resolve(true)
      })
    },
    clear() {
      this.newMapObject = []
      this.seeMapObject = []
      this.model.attributes = null
      console.log(this.model.attributes)
    },
    //获取图片
    getImgUrl(record) {
      this.imgbase = ''
      if (record && record.unqualifiedImg) {
        let params = record.unqualifiedImg
        console.log(record.unqualifiedImg)
        getActionImg('systemConfig/static/' + params).then(res => {
          const captchaImg = window.URL.createObjectURL(res)
          this.imgbase = captchaImg
        })
      }
    },

    //map转化为对象
    _strMapToObj(strMap) {
      let obj = Object.create(null)
      for (let [k, v] of strMap) {
        obj[k] = v
      }
      return obj
    },
    //规格数据接口
    getModelList() {
      getModelList().then(res => {
        if (res.code == 10000) {
          this.modelArr = res.data.records
        }
      })
    },
    //删除规格型号
    // deleteDomList(indexs) {
    //   this.DomList.splice(indexs, 1)
    // },
    //新增规格型号
    addNewModel() {
      this.newMap = new Map()
      this.vaArr.push(this.value)
      this.guiArr.push(this.guiG)
      for (var i = 0; i < this.vaArr.length; i++) {
        this.newMap.set(this.guiArr[i], this.vaArr[i])
      }
      this.newMapObject = JSON.stringify(this._strMapToObj(this.newMap))
      this.value = ''
      this.guiGeValue = ''
      console.log(this.newMapObject)
    },
    //获取类型
    getList() {
      getDateList({ testType: this.$router.currentRoute.name }).then(res => {
        if (res.code == 10000) {
          this.purchaseTest = res.data.records
        }
      })
    },
    add() {
      this.edit()
    },
    //选择类型
    log(item) {
      this.selectValue = item.typeName
    },
    //选择产品规格
    checkout(item) {
      this.selectModel = item
      this.guiG = item.attributeName
    },
    edit(record) {
      this.form.resetFields()
      this.defaultFileList = []
      this.guiGeValue = ''
      this.newMapObject = ''
      this.model = Object.assign({}, record)
      this.visible = true
      //   this.getImgUrl(record)
      this.$nextTick(() => {
        setTimeout(() => {
          //如果有record则走编辑,日期回显
          if (record) {
            console.log('record', record)
            this.record = record
            var testDate = this.$moment(this.model.testDate)
            this.form.setFieldsValue({ testDate: testDate })
            this.newMapObject = record.attributes
            this.seeMapObject = record.attributes
            console.log(this.seeMapObject)
            if (record.bizFileList && record.bizFileList != null) {
              for (let i = 0; i < record.bizFileList.length; i++) {
                let item = record.bizFileList[i]
                let obj = {
                  uid: item.id,
                  fileUrl: item.fileUrl,
                  name: item.fileName
                }
                this.defaultFileList.push(obj)
              }
              console.log(this.defaultFileList)
              for (let j = 0; j < this.defaultFileList.length; j++) {
                let params = this.defaultFileList[j].fileUrl
                getActionImg('systemConfig/static/' + params).then(res => {
                  console.log(res)
                  const captchaImg = window.URL.createObjectURL(res)
                  this.baseList.push({
                    fileUrl: captchaImg,
                    name: this.defaultFileList[j].name
                  })
                })
              }
            }
            // getImg(params) {
            //   getActionImg('systemConfig/static/' + params).then(res => {
            //     console.log(res)
            //     const captchaImg = window.fileUrl.createObjectURL(res)
            //     this.previewImage = captchaImg

            //     console.log(this.previewImage, 'imgbase')
            //     this.previewVisible = true
            //   })
            // },
            // //如果有图片
            // if (record.unqualifiedImg) {
            //   this.defaultFileList.push({
            //     uid: '2',
            //     name: `${record.unqualifiedImg}`,
            //     status: 'done',
            //     fileUrl: window._CONFIG['domianURL'] + `${record.unqualifiedImg}`
            //   })
            // }
          }
          this.form.setFieldsValue(
            pick(
              this.model,
              'productType',
              'testNum',
              'vendor',
              'unqualifiedNum',
              'disposal',
              'productName',
              'unqualifiedContent',
              'voucher'
            )
          )
          autoJumpNextInput('customerModal')
        }, 400)
      })
    },
    close() {
      this.defaultFileList = []
      this.baseList = []
      this.$emit('close')
      this.visible = false
      this.isReadOnly = false
    },
    handleOk() {
      console.log(this.model, this.defaultFileList, '402')

      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          formData.testDate = this.$moment(formData.testDate).format('YYYY-MM-DD')
          formData.unqualifiedNum = Number(formData.unqualifiedNum)
          formData.testNum = Number(formData.testNum)
          if (this.newMapObject && this.newMapObject.length > 0) {
            formData.attributes = this.newMapObject
          }
          formData.qualifiedRate = ((formData.testNum - formData.unqualifiedNum) / formData.testNum) * 10000
          formData.testType = this.$router.currentRoute.name
          //   if (this.defaultFileList[0] && this.defaultFileList[0].name) {
          //     formData.unqualifiedImg = this.defaultFileList[0].name
          //   } else {
          //     formData.unqualifiedImg = this.defaultFileList[0]
          //   }
          //   this.defaultFileList.length > 0 ? this.defaultFileList[this.defaultFileList.length - 1] : ''
          formData.bizFileList = this.defaultFileList
          console.log(this.model)
          let obj
          if (!this.model.testId) {
            obj = addProduct(formData)
          } else {
            obj = addProduct(formData)
          }
          obj
            .then(res => {
              if (res.code === 200 || res.code === 10000) {
                this.$message.success(res.message)
                that.confirmLoading = false
                this.$emit('ok')
                this.value = ''
              } else {
                this.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then(res => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback('名称已经存在')
          }
        } else {
          callback(res.data)
        }
      })
    },
    //上传
    handleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file)
        // console.log(info.file, info.fileList)
      }
      console.log(info)
      if (info.file.status === 'done') {
        if (info.file.response) {
          console.log(info)
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 200 || info.file.response.code === 10000) {
            this.$message.success(`${info.file.name} 文件上传成功` || info.file.response.result)
            // this.defaultFileList.splice(0)
            // let a = info.file.response.result.indexOf(this.fileName.bizPath)
            console.log(info.file.response.result)
            let obj = {
              fileUrl: info.file.response.data,
              fileName: info.file.name
            }
            this.defaultFileList.push(obj)
          } else {
            this.$message.warning(info.file.response.message)
          }
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.result}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      } else if (info.file.status === 'removed') {
        for (let i = 0; i < this.defaultFileList.length; i++) {
          console.log('582', this.defaultFileList[i].fileUrl, info.file.fileUrl)
          if (info.file.response) {
            if (this.defaultFileList[i].fileUrl == info.file.response.data) {
              this.defaultFileList.splice(i, 1)
            }
          } else {
            if (this.defaultFileList[i].fileUrl == info.file.fileUrl) {
              console.log('584')
              this.defaultFileList.splice(i, 1)
            }
          }
        }
      }
      console.log('defaultFileList:', this.defaultFileList)
    },
    // 预览
    // handlePreview(file) {
    //   console.log(file, 'prfile')
    //   this.previewImage = file.fileUrl || file.response.data
    //   this.previewVisible = true
    // },
    getImg(params) {
      getActionImg('systemConfig/static/' + params).then(res => {
        console.log(res)
        const captchaImg = window.URL.createObjectURL(res)
        this.previewImage = captchaImg

        console.log(this.previewImage, 'imgbase')
        this.previewVisible = true
      })
    },
    async handlePreview(file) {
      console.log(file, 'prfile')
      if (!file.fileUrl && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.response.data
      //   this.previewImage = file.fileUrl || file.preview
      this.getImg(this.previewImage)
      console.log(this.previewImage)
      //   this.previewVisible = true
    },
    handleCancels() {
      this.previewVisible = false
    }
  }
}
</script>
<style scoped>
#imgSyle {
  width: 100%;
  height: 100%;
}
</style>
